<?php
namespace app\index\controller;
use \think\Controller;
use \think\View;
use app\index\model\ImgTest;
use app\index\model\PhotoModel;
use app\index\model\LoginModel;
// 定义常量
const APP_ID = '9869527';
const API_KEY = 'kW6DdHOS3aR55p8bkwFosF8y';
const SECRET_KEY = 'BLw2FPDAsG7rI7EQ3XOZnHsGwibEhG7g';

class Face extends Controller
{

    public function index()
    {
        // if(!session('user_no')){//未登录时跳转至登录页面
        //     return "<script>location.href='".url('index/login/index')."'</script>";
        // }

        $this->assign('username',session('username'));
        return $this->fetch('index');
    }

	//24.c73d0cf862954c5340873fa5a9834f95.2592000.1502415615.282335-9869527
	function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
        
        return $data;
    }

    public function test_result(){
        if ((($_FILES["photo"]["type"] == "image/jpg") || ($_FILES["photo"]["type"] == "image/png")
                || ($_FILES["photo"]["type"] == "image/jpeg"))
                && ($_FILES["photo"]["size"] < 2*1024*1024)){
                if ($_FILES["photo"]["error"] > 0){
                    echo "发生了错误，错误码: " . $_FILES["photo"]["error"] . "<br /><a href='javascript:history.go(-1);'>返回</a>";exit;
                }else{
                    $file_name = date('YmdHis').$_FILES["photo"]["name"];
                    move_uploaded_file($_FILES["photo"]["tmp_name"],
                    $_SERVER['DOCUMENT_ROOT']."/robot/public/static/upload_img/".$file_name);
                    //echo "Stored in: " . $_SERVER['DOCUMENT_ROOT']."/static/upload_img/". $_FILES["photo"]["name"];
                    //echo "<script>location.href='test_result?img=".$_SERVER['DOCUMENT_ROOT']."/static/upload_img/".$file_name."'</script>";
                    
            }
        }else{
            echo "选择不是图片或者图片大小超限制（2M）！<br><a href='javascript:history.go(-1);'>返回</a>";exit;
    }
        $image_url = $_SERVER['DOCUMENT_ROOT']."/robot/public/static/upload_img/".$file_name;
        $insert_data['user_id'] = session("user_id");
        $insert_data['url'] = $image_url;
        $insert_data['file_name'] = $file_name;
        $photo = new \app\index\model\PhotoModel();
        $photo_data = $photo->save($insert_data, 1);
        
    	$token = '24.c73d0cf862954c5340873fa5a9834f95.2592000.1502415615.282335-9869527';
    	$url = 'https://aip.baidubce.com/rest/2.0/face/v1/detect?access_token='.$token;
    	$img = file_get_contents($image_url);
    	$img = base64_encode($img);
    	$bodys = array("image"=>$img,'face_fields'=>'age,beauty,expression,faceshape,gender,qualities,face_probability,glasses,race,qualities,human');
        $request = new Face();
    	$res = $request->request_post($url, $bodys);
        $res = json_decode($res,true);
        //var_dump($res['result'][0]['qualities']['type']['human']);exit;
        //$result = $res->result;
        if($res['result_num']==0){
            echo "照片中未检测到人脸！<a href='javascript:history.go(-1);'>返回</a>";exit;
        }
        
        
        //echo "人脸数目：".$res->result_num."<br>";
        if($res['result'][0]['expression']=='0'){
            $res['result'][0]['expression'] = '不笑';
        }elseif($res['result'][0]['expression']=='1'){
            $res['result'][0]['expression'] = '微笑';
        }else{
            $res['result'][0]['expression'] = '大笑';
        }

        if($res['result'][0]['glasses']=='0'){
            $res['result'][0]['glasses'] = '无眼镜';
        }elseif($res['result'][0]['glasses']=='1'){
            $res['result'][0]['glasses'] = '普通眼镜';
        }else{
            $res['result'][0]['glasses'] = '墨镜';
        }
        if($res['result'][0]['beauty']<20){
            $res['result'][0]['explain'] = '很丑';
        }elseif($res['result'][0]['beauty']<30){
            $res['result'][0]['explain'] = '丑';
        }elseif ($res['result'][0]['beauty']<40) {
            $res['result'][0]['explain'] = '一般';
        }elseif ($res['result'][0]['beauty']<50) {
            $res['result'][0]['explain'] = '一般美';
        }elseif ($res['result'][0]['beauty']<60) {
            $res['result'][0]['explain'] = '美';
        }elseif ($res['result'][0]['beauty']<70){
            $res['result'][0]['explain'] = '很美';
        }else{
             $res['result'][0]['explain'] = '仙女';
        }

        if($res['result'][0]['gender']=='male'){
            $res['result'][0]['gender'] = "男";
        }else{
            $res['result'][0]['gender'] = "女";
        }

        if($res['result'][0]['qualities']['type']['human']>0.5){
            $res['result'][0]['qualities']['type']['human'] = '真实人脸';
        }else{
            $res['result'][0]['qualities']['type']['human'] = '卡通人脸';
        }

        if($res['result'][0]['race']=='yellow'){
            $res['result'][0]['race'] = '黄种人';
        }elseif($res['result'][0]['race']=='white'){
            $res['result'][0]['race'] = '白种人';
        }elseif($res['result'][0]['race']=='black'){
            $res['result'][0]['race'] = '黑种人';
        }else{
            $res['result'][0]['race'] = '阿拉伯人';
        }
        $this->assign("file_name",$file_name);
        $this->assign("result_num",$res['result_num']);
        $this->assign("gender",$res['result'][0]['gender']);
        $this->assign("age",$res['result'][0]['age']);
        $this->assign("beauty",$res['result'][0]['beauty']);
        $this->assign("face_probability",$res['result'][0]['face_probability']);
        $this->assign("expression",$res['result'][0]['expression']);
        $this->assign("glasses",$res['result'][0]['glasses']);
        $this->assign("explain",$res['result'][0]['explain']);
        $this->assign("human",$res['result'][0]['qualities']['type']['human']);
        $this->assign("race",$res['result'][0]['race']);

        return $this->fetch('result');

    	//var_dump($res['result'][0]['gender']);
        // require_once 'AipFace.php';



        // // 初始化ApiFace
        // $aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // // 定义参数变量
        // $option = array(
        //   'max_face_num' => 1,
        //   'face_fields' => 'expression'
        // );

        // // 调用人脸属性识别接口
        // $result = $aipFace->detect(file_get_contents('C:\Users\DH004\Desktop\test2.jpg'), $option);
        }	

        public function test()
        {
            //echo $_FILES["photo"]["type"];echo $_FILES["photo"]["size"];
            if ((($_FILES["photo"]["type"] == "image/jpg") || ($_FILES["photo"]["type"] == "image/png")
                || ($_FILES["photo"]["type"] == "image/jpeg"))
                && ($_FILES["photo"]["size"] < 2*1024*1024)){
                if ($_FILES["photo"]["error"] > 0){
                    echo "Return Code: " . $_FILES["photo"]["error"] . "<br />";
                }else{
                    $file_name = date('YmdHis').$_FILES["photo"]["name"];
                    move_uploaded_file($_FILES["photo"]["tmp_name"],
                    $_SERVER['DOCUMENT_ROOT']."/static/upload_img/".$file_name);
                    //echo "Stored in: " . $_SERVER['DOCUMENT_ROOT']."/static/upload_img/". $_FILES["photo"]["name"];
                    echo "<script>location.href='test_result?img=".$_SERVER['DOCUMENT_ROOT']."/static/upload_img/".$file_name."'</script>";
                    
            }
        }else{
            echo "请选择一张照片！";
        }
    }

    public function photoList()
    {
        
        // $identity = new \app\index\model\LoginModel();
        // $user_info = $identity->get_user_info(session('user_no'));
        // if($user_info && $user_info['identity']=='2'){
            $photo = new \app\index\model\PhotoModel();
            $photo_list = $photo->get_photo_list();//var_dump($photo_list);exit;
            $this->assign("photo_list",$photo_list);
            return $this->fetch('allPhoto');
        // }else{
        //     return $this->error("您不是管理员，您没有权限查看此页面！如需管理员权限，请联系我，邮箱：1012789729@qq.com");
        // }
        
    }

    public function photoInfo()
    {
        $file_name = $_REQUEST['file_name'];
        $photo = new \app\index\model\PhotoModel();
        $photo_info = $photo->get_photo_info($file_name);//var_dump($photo_list);exit;
        //var_dump(json_encode($photo_info));exit;
        //return json_encode($photo_info);
         if(!$photo_info){
            return json(array('code'=>'-30001','msg'=>"图片不存在或已被删除！",'data'=>array()));
        }
        return json(array('code'=>'0','msg'=>"成功",'data'=>$photo_info));
    }

    public function jsonTest()
    {
        $file_name = $_REQUEST['file_name'];
        $photo = new \app\index\model\PhotoModel();
        $photo_info = $photo->get_photo_info($file_name);
        if(!$photo_info){
            return json(array('code'=>'-30001','msg'=>"图片不存在或已被删除！",'data'=>array()));
        }
        $data = array();

        $image_url = $_SERVER['DOCUMENT_ROOT']."/robot/public/static/upload_img/".$file_name;
        // $insert_data['url'] = $image_url;
        // $insert_data['file_name'] = $file_name;
        // $photo = new \app\index\model\PhotoModel();
        // $photo_data = $photo->save($insert_data, 1);
        
        $token = '24.c73d0cf862954c5340873fa5a9834f95.2592000.1502415615.282335-9869527';
        $url = 'https://aip.baidubce.com/rest/2.0/face/v1/detect?access_token='.$token;
        $img = file_get_contents($image_url);
        $img = base64_encode($img);
        $bodys = array("image"=>$img,'face_fields'=>'age,beauty,expression,faceshape,gender,qualities,face_probability,glasses,race,qualities,human');
        $request = new Face();
        $res = $request->request_post($url, $bodys);
        $res = json_decode($res,true);
        //var_dump($res['result'][0]['qualities']['type']['human']);exit;
        //$result = $res->result;
        if($res['result_num']==0){
            return json(array('code'=>'-30002','msg'=>"照片中未检测到人脸！",'data'=>array())); 
        }
        $data['result_num'] = $res['result_num'];
        $data['age'] = $res['result'][0]['age'];
        $data['face_probability'] = $res['result'][0]['face_probability'];
        
        //echo "人脸数目：".$res->result_num."<br>";
        if($res['result'][0]['expression']=='0'){
            // $res['result'][0]['expression'] = '不笑';
            $data['expression'] = '不笑';
        }elseif($res['result'][0]['expression']=='1'){
            $data['expression'] = '微笑';
        }else{
            $data['expression'] = '大笑';
        }

        if($res['result'][0]['glasses']=='0'){
            $data['glasses'] = '无眼镜';
        }elseif($res['result'][0]['glasses']=='1'){
            $data['glasses'] = '普通眼镜';
        }else{
            $data['glasses'] = '墨镜';
        }
        if($res['result'][0]['beauty']<20){
            $data['beauty'] = '很丑';
        }elseif($res['result'][0]['beauty']<30){
            $data['beauty'] = '丑';
        }elseif ($res['result'][0]['beauty']<40) {
            $data['beauty'] = '一般';
        }elseif ($res['result'][0]['beauty']<50) {
            $data['beauty'] = '一般美';
        }elseif ($res['result'][0]['beauty']<60) {
            $data['beauty'] = '美';
        }elseif ($res['result'][0]['beauty']<70){
            $data['beauty'] = '很美';
        }else{
             $data['beauty'] = '仙女';
        }
        $data['score'] = $res['result'][0]['beauty'];

        if($res['result'][0]['gender']=='male'){
            $data['gender'] = "男";
        }else{
            $data['gender'] = "女";
        }

        if($res['result'][0]['qualities']['type']['human']>0.5){
            $data['human'] = '真实人脸';
        }else{
            $data['human'] = '卡通人脸';
        }

        if($res['result'][0]['race']=='yellow'){
            $data['race'] = '黄种人';
        }elseif($res['result'][0]['race']=='white'){
            $data['race'] = '白种人';
        }elseif($res['result'][0]['race']=='black'){
            $data['race'] = '黑种人';
        }else{
            $data['race'] = '阿拉伯人';
        }
        return json(array('code'=>0,'msg'=>'成功','data'=>$data));
    }



}